package impl

import (
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/dto"
	contract3 "git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/repository/common/contract"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/service/bigdata/contract"
	"github.com/gin-gonic/gin"
	"strings"
)

type WriteService struct {
	srCommonRepo contract3.SrCommonRepoIface
}

func NewWriteService(
	srCommonRepo contract3.SrCommonRepoIface,
) contract.WriteServiceIface {
	return &WriteService{
		srCommonRepo: srCommonRepo,
	}
}

func (w *WriteService) SaveRCCContactInfo(ctx *gin.Context, RCCContactInfoList []*dto.RCCContactInfo) error {
	if len(RCCContactInfoList) == 0 {
		return nil
	}

	querySql := fmt.Sprintf("select * from dwd_rcc_contact_info where src_id = '%s' limit 1000;", common.EscapeStr(RCCContactInfoList[0].SrcId))
	list, err := w.srCommonRepo.GetList(ctx.Request.Context(), querySql)
	if err != nil {
		return err
	}

	insertValues := make([]string, 0)
	for _, item := range RCCContactInfoList {
		item.PersonPhone = strings.Trim(item.PersonPhone, " ")

		isDuplicate := false
		// 使用company_name和person_phone来判重
		for _, existedContactInfo := range list {
			existedCompanyName, _ := existedContactInfo["company_name"]
			existedPersonPhone, _ := existedContactInfo["person_phone"]
			if item.CompanyName == existedCompanyName && item.PersonPhone == existedPersonPhone {
				isDuplicate = true
				break
			}
		}

		if !isDuplicate && item.PersonPhone != "" {
			item.SrcId = common.EscapeStr(item.SrcId)
			item.ProjectId = common.EscapeStr(item.ProjectId)
			item.RccProjectName = common.EscapeStr(item.RccProjectName)
			item.CompanyName = common.EscapeStr(item.CompanyName)
			item.CompanyAddress = common.EscapeStr(item.CompanyAddress)
			item.PersonName = common.EscapeStr(item.PersonName)
			item.PersonPhone = common.EscapeStr(item.PersonPhone)
			item.PersonPosition = common.EscapeStr(item.PersonPosition)
			item.PersonRole = common.EscapeStr(item.PersonRole)
			insertValues = append(insertValues, fmt.Sprintf("(%d, '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', %d)", item.Id, item.SrcId, item.ProjectId, item.RccProjectName, item.CompanyName, item.CompanyAddress, item.PersonName, item.PersonSexy, item.PersonPhone, item.PersonPosition, item.PersonRole, item.SourceType))
		}
	}

	if len(insertValues) > 0 {
		sql := fmt.Sprintf("INSERT INTO `dwd_rcc_contact_info` values %s;", strings.Join(insertValues, ","))
		_, err := w.srCommonRepo.Save(ctx.Request.Context(), sql)
		if err != nil {
			return fmt.Errorf("SaveRCCContactInfo err: %s", err.Error())
		}
	}

	return nil
}
